package com.busionline.wotu.baselibrary.dialog;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * 项目名称：joke
 * 类描述：专门处理界面
 * 创建人：chenwuchao
 * 创建时间：2017/5/9 15:03
 */
class DialogViewHelper {
    private View contentView;
    private SparseArray<WeakReference<View>> mViews;

    public DialogViewHelper() {
        mViews = new SparseArray<>();
    }

    public DialogViewHelper(Context mContext, int mViewLayoutResId) {
        this();
        contentView = LayoutInflater.from(mContext).inflate(mViewLayoutResId, null);
    }



    /**
     * 设置布局
     *
     * @param mView
     */
    public void setContentView(View mView) {
        contentView = mView;
    }

    /**
     * 设置文本
     * @param resId
     * @param charSequence
     */
    public void setText(int resId, CharSequence charSequence) {
        TextView textView = getView(resId);
        if(textView != null){
            textView.setText(charSequence);
        }
    }

    /**
     * 在集合中通过id找到控件，没有就保存进集合中
     * @return
     * @param resId
     */
    public  <T extends View>T getView(int resId) {
        //必须这么写 mViews.get(resId).get();会直接崩溃
        WeakReference<View> weakReference = mViews.get(resId);
        View view = null;
        if(weakReference != null){
             view = weakReference.get();
        }

        if(view == null){
        //该id对应的控件集合中不存在
            view = contentView.findViewById(resId);
            if(view != null){
                //控件存在,存入集合中
                mViews.put(resId, new WeakReference<>(view));
            }
        }
        return (T) view;
    }

    /**
     * 设置点击事件
     * @param resId
     * @param onClickListener
     */
    public void setOnClickListener(int resId, View.OnClickListener onClickListener) {
        View view = getView(resId);
        if(view != null){
            view.setOnClickListener(onClickListener);
        }
    }

    /**
     * 获得dialog布局
     * @return
     */
    public View getContentView() {
        return contentView;
    }
}
